<template>
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
    <el-breadcrumb-item :to="{ path: '/admin' }">
      <i class="el-icon-s-promotion"></i> 后台管理
    </el-breadcrumb-item>
    <el-breadcrumb-item>餐品列表</el-breadcrumb-item>
  </el-breadcrumb>

  <el-divider></el-divider>

  <el-card style="float: left ;width: 100%; height: 100%;margin: 10px">
    <el-divider content-position="left">餐品表格</el-divider>

<!--    添加餐品按钮-->
    <el-button type="warning" icon="el-icon-edit" @click="openAddNewDialog()">添加餐品</el-button>
<!--弹出的新增餐品的表格-->
    <el-dialog title= "新增餐品"  :visible.sync="addNewFormVisible">
      <el-form :model="addNewForm" :rules="rules" ref="addNewForm" >
        <el-form-item label="餐品名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="addNewForm.name"></el-input>
        </el-form-item>
        <el-form-item label="餐品价格" prop="price" :label-width="formLabelWidth">
          <el-input v-model="addNewForm.price"></el-input>
        </el-form-item>
        <el-form-item label="餐品图片" :label-width="formLabelWidth">
          <el-upload
              action="http://localhost:8080/upload"
              name="picFile"
              limit="1"
              list-type="picture-card"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>


      <!-- 新增餐品的按钮       -->
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="warning" @click="addNewSubmitForm('addNewForm')">新增餐品</el-button>
        <el-button @click="addNewFormVisible = false">取 消</el-button>
      </div>

    </el-dialog>


<!--    弹出的修改餐品的表单-->

    <el-dialog title= "修改餐品"  :visible.sync="dialogVisible">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="80px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="editForm.name" type="text"></el-input>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="editForm.price" type="text"></el-input>
        </el-form-item>
        <el-form-item label="菜品图片">
          <template slot-scope="scope">
            <img :src="require('../../../assets/food/'+editForm.url)" width="300" height="300"/>
          </template>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
              action="http://localhost:8080/upload"
              name="picFile"
              limit="1"
              list-type="picture-card"
              :on-success="edithandleSuccess"
              :on-preview="edithandlePictureCardPreview"
              :on-remove="edithandleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="editdialogVisible">
            <img width="100%" :src="editdialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="updateForm('editForm')">修改菜品</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


<!--    餐品列表-->
    <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :data="this.foodArr">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index"
                       :index="indexMethod"
                       label="编号" align="center" width="50"></el-table-column>
      <el-table-column prop="name" label="餐品名称" header-align="center"></el-table-column>
      <el-table-column prop="price" label="餐品价格" width="100" header-align="center"></el-table-column>
      <el-table-column label="餐品图片" width="100" header-align="center">
        <!--如果表格的列显示的内容不是来自于数组里面对象的属性,而是显示一些
        其它的标签组成的内容时,需要自定义列-->
        <!--自定义列 必须添加template标签-->
        <template slot-scope="scope">
            <div class="demo-type">
              <el-avatar :size="50" :src="require('../../../assets/food/'+scope.row.url)" @error="true">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
              </el-avatar>
            </div>
          </template>
      </el-table-column>

      <!--操作列-->
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="warning"
              @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="info" icon="el-icon-delete"
              @click="openDeleteConfirm(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <div class="block">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="reformPage.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="reformPage.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>


  </el-card>

</div>
</template>

<script>
export default {
  name: "FoodListView",
  data: function () {
    return {
     reformPage:{ page:1,
                  pageSize:10},
      total:10,
      formLabelWidth: '120px',
      dialogImageUrl: '',
      dialogVisible: false,
      foodArr: [],
      food:[],
      addNewFormVisible: false,
      dialogFormVisible: false,
      rules: {
        name: [{ required: true, message: '请输入餐品名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入餐品价格', trigger: 'blur' }, {pattern: /^([1-9]\d*(\.\d{1,2})?)|(^0(\.\d{1,2})?$)/, message: '价格必须是小数', trigger: 'blur'}],
      },
      addNewForm:{name:'',price:'',url:''},
      editForm:{id:'',name:'',price:'',url:''},
      editdialogImageUrl: '',
      editdialogVisible: false,



    }
  },
  methods: {
    indexMethod(index)
    {
      return (this.reformPage.page-1)*this.reformPage.pageSize+index+1;
    },
    loadFoodList(){
      let url = 'http://localhost:8080/foods/list-by-page?'+this.qs.stringify(this.reformPage);

      this.axios.create(
          {
            headers:{
              "Authorization":localStorage.getItem("jwt")
            }
          }
      ).get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          console.log( responseBody.data.list);
          this.total = responseBody.data.total;
          this.foodArr = responseBody.data.list;
        }
        console.log("foodArr!!!!!:{}",this.foodArr)
        console.log("reformPage.page:{}",this.reformPage.page)
        console.log("reformPage.pageSize:{}",this.reformPage.pageSize)
      });
    },


    handleSizeChange(val) {
      this.reformPage.pageSize =val;
      this.loadFoodList();
    },
    handleCurrentChange(val) {
      this.reformPage.page =val;
      this.loadFoodList();
    },



    updateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:8080/foods/update';
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.editForm);
          console.log('formData = ' + formData);

          this.axios.create(
              {
                headers:{
                  "Authorization":localStorage.getItem("jwt")
                }
              }
          )
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.loadFoodList();
              this.dialogVisible = false;
              this.$message({message: '修改餐品成功！', type: 'success'});
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    edithandleRemove(file, fileList) {
      console.log(file, fileList);
      this.editForm.url="";
    },
    edithandlePictureCardPreview(file) {
      this.editdialogImageUrl = file.url;
      this.editdialogVisible = true;
    },
    edithandleSuccess(response,file,fileList){
      this.editForm.url = response;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.addNewForm.url="";
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response,file,fileList){
      this.addNewForm.url = response;
      console.log("re:{}",response)
    },
    openAddNewDialog(){
      this.addNewFormVisible=true;
    },
    openDeleteConfirm(food){
      console.log(this.food);
      console.log(food);
      let message = '此操作将永久删除【' + food.name+ '】餐品，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(food);
      }).catch(() => {
      });
    },
    openEditDialog(food) {
      this.dialogVisible = true;
      let url = 'http://localhost:8080/foods/' + food.id;
      console.log('url = ' + url);
      this.axios.create(
              {
                headers:{
                  "Authorization":localStorage.getItem("jwt")
                }
              }
          )
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.editForm = responseBody.data;
          console.log("修改的对象:{}",this.editForm);

        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadFoodList();
            }
          });
        }
      });
    },

    handleDelete(food){//餐品删除方法
      console.log(food.id);
      let url = 'http://localhost:8080/foods/' + food.id + "/delete";
      console.log('url = ' + url);
      this.axios.create(
          {
            headers:{
              "Authorization":localStorage.getItem("jwt")
            }
          }
      )
      .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.loadFoodList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadFoodList();
            }
          });

        } else {
          this.$message.error(responseBody.message);
        }
      });
    },

    addNewSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:8080/foods/add-new';
          console.log('url = ' + url);
          console.log('addNewForm={}', this.addNewForm)
          let formData = this.qs.stringify(this.addNewForm);
          console.log('formData = ' + formData);
          this.axios.create(
              {
                headers:{
                  "Authorization":localStorage.getItem("jwt")
                }
              }
          )
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.$message({
                message: '餐品提交成功！',
                type: 'success'
              });
              this.resetForm(formName);
              this.loadFoodList();
              this.addNewFormVisible=false;
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  mounted() {
    this.loadFoodList();
  }




}
</script>

<style scoped>

</style>